package com.work.yshop.mvp.presenter;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.work.yshop.model.Product;
import com.work.yshop.mvp.contract.SellerHomeContract;
import com.work.yshop.provider.ProductProvider;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 卖家首页Presenter实现
 */
public class SellerHomePresenter implements SellerHomeContract.Presenter {

    private static final String TAG = "SellerHomePresenter";
    private SellerHomeContract.View view;
    private Context context;

    public SellerHomePresenter(Context context) {
        this.context = context;
    }

    @Override
    public void attachView(SellerHomeContract.View view) {
        this.view = view;
    }

    @Override
    public void detachView() {
        this.view = null;
        this.context = null;
    }

    @Override
    public void loadData() {
        if (view == null || context == null) return;

        try {
            view.showLoading();
            ContentResolver resolver = context.getContentResolver();

            // 查询卖家的商品总数
            Cursor countCursor = resolver.query(
                    ProductProvider.CONTENT_URI,
                    new String[]{"COUNT(*) as count"},
                    "seller_id = ?",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())},
                    null
            );

            int productCount = 0;
            if (countCursor != null) {
                if (countCursor.moveToFirst()) {
                    productCount = countCursor.getInt(0);
                }
                countCursor.close();
            }

            // 更新商品数量显示
            view.showProductCount(productCount);

            // 加载在售商品数据（按上架时间倒序，最多显示3个）
            Cursor cursor = resolver.query(
                    ProductProvider.CONTENT_URI,
                    null,
                    "seller_id = ? AND status = 1",
                    new String[]{String.valueOf(UserSession.getInstance().getUserId())},
                    "publish_date DESC LIMIT 3"
            );

            List<Product> recentProducts = new ArrayList<>();

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
                    String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
                    String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
                    double price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
                    double originalPrice = cursor.getDouble(cursor.getColumnIndexOrThrow("original_price"));
                    String unit = cursor.getString(cursor.getColumnIndexOrThrow("unit"));
                    int stock = cursor.getInt(cursor.getColumnIndexOrThrow("stock"));
                    int salesCount = cursor.getInt(cursor.getColumnIndexOrThrow("sales_count"));
                    String category = cursor.getString(cursor.getColumnIndexOrThrow("category"));
                    String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
                    int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));

                    Product product = new Product();
                    product.setId(id);
                    product.setName(name);
                    product.setDescription(description);
                    product.setPrice(price);
                    product.setOriginalPrice(originalPrice);
                    product.setUnit(unit);
                    product.setStock(stock);
                    product.setSalesCount(salesCount);
                    product.setCategory(category);
                    product.setImageUrl(imageUrl);
                    product.setStatus(status);

                    recentProducts.add(product);
                }
                cursor.close();
            }

            // 更新适配器数据
            view.showProducts(recentProducts);

            // 设置销售额和订单数（这里可以从订单表中查询，暂时使用模拟数据）
            view.showSalesAmount("¥ 12,580.00");
            view.showOrderCount("156");

            view.hideLoading();
        } catch (Exception e) {
            Log.e(TAG, "加载数据失败", e);
            view.hideLoading();
            view.showError("加载数据失败: " + e.getMessage());
        }
    }

    @Override
    public void editProduct(Product product) {
        if (view == null) return;
        view.navigateToProductEdit(product.getId());
    }

    @Override
    public void toggleProductStatus(Product product) {
        if (view == null || context == null) return;

        try {
            // 更新商品状态
            ContentValues values = new ContentValues();
            values.put("status", product.getStatus() == 1 ? 0 : 1);

            ContentResolver resolver = context.getContentResolver();
            int updatedRows = resolver.update(
                    Uri.withAppendedPath(ProductProvider.CONTENT_URI, String.valueOf(product.getId())),
                    values,
                    null,
                    null
            );

            if (updatedRows > 0) {
                String message = product.getStatus() == 1 ? "商品已下架" : "商品已上架";
                view.showSuccess(message);
                
                // 重新加载数据
                loadData();
            } else {
                view.showError("操作失败，请重试");
            }
        } catch (Exception e) {
            Log.e(TAG, "更新商品状态失败", e);
            view.showError("更新商品状态失败: " + e.getMessage());
        }
    }

    @Override
    public void navigateToProductList() {
        if (view != null) {
            view.navigateToProductList();
        }
    }

    @Override
    public void navigateToOrderManage() {
        if (view != null) {
            view.navigateToOrderManage();
        }
    }

    @Override
    public void navigateToPublishProduct() {
        if (view != null) {
            view.navigateToPublishProduct();
        }
    }
} 